package com.renren.webmaven2.service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.renren.eliya.domain.BigClass;
import com.renren.eliya.domain.BreadPic;
import com.renren.eliya.domain.BreadPrice;
import com.renren.eliya.domain.JoinUs;
import com.renren.eliya.domain.MyBread;
import com.renren.eliya.domain.MyComment;
import com.renren.eliya.domain.SmallClass;
import com.renren.yx.base.dao.daoutil.InitDao;

/**
 * write
 * 
 * @author jizhong.yang
 * @version V1.0
 */

@Service
@SuppressWarnings("unchecked")
public class BreadService {

	@Autowired
	private MonitorService monitorService;

	@Autowired
	private SmallClassService smallClassService;
	@Autowired
	private FileUploadService fileUploadService;

	public int add(String name, String code, String content, String heavy, String size, String stock, String taste, String big_class_id, String small_class_id, String condition, String people,
			String sendTime, String price, String bigPicUrl, String smallPicUrl, String breadId) {
		try {
			if (StringUtils.isBlank(breadId)) {
				addNew(name, code, content, heavy, size, stock, taste, big_class_id, small_class_id, condition, people, sendTime, price);
			} else {
				update(name, code, content, heavy, size, stock, taste, big_class_id, small_class_id, condition, people, sendTime, price, breadId);
			}
			monitorService.getBread();
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	private void update(String name, String code, String content, String heavy, String size, String stock, String taste, String big_class_id, String small_class_id, String condition, String people,
			String sendTime, String price, String breadId) {
		MyBread myBread = (MyBread) InitDao.getDao().getEntity(MyBread.class, Integer.valueOf(breadId));
		init(name, code, content, heavy, size, stock, taste, big_class_id, small_class_id, condition, people, sendTime, price, myBread);
		InitDao.getDao().updateEntity(myBread);
	}

	private void addNew(String name, String code, String content, String heavy, String size, String stock, String taste, String big_class_id, String small_class_id, String condition, String people,
			String sendTime, String price) {
		MyBread bread = new MyBread();
		init(name, code, content, heavy, size, stock, taste, big_class_id, small_class_id, condition, people, sendTime, price, bread);
		InitDao.getDao().addEntity(bread);
	}

	private void init(String name, String code, String content, String heavy, String size, String stock, String taste, String big_class_id, String small_class_id, String condition, String people,
			String sendTime, String price, MyBread bread) {
		bread.setBigClassId(Integer.valueOf(big_class_id));
		// bread.setBigPicUrl(bigPicUrl);
		bread.setCode(code);
		bread.setMyCondition(condition);
		bread.setContent(content);
		bread.setHeavy(heavy);
		bread.setName(name);
		bread.setPeople(people);
		bread.setPrice(price);
		bread.setSendTime(sendTime);
		bread.setMySize(size);
		bread.setSmallClassId(Integer.valueOf(small_class_id));
		// bread.setSmallPicUrl(smallPicUrl);
		bread.setStock(stock);
		bread.setTaste(taste);
		bread.setCreateTime(new Timestamp(System.currentTimeMillis()));
	}

	public int del(Integer id) {
		try {
			MyBread bread = (MyBread) InitDao.getDao().getEntity(MyBread.class, id);
			InitDao.getDao().delEntity(bread);
			monitorService.getBread();
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	public int update(String bigClassName, Integer weight, Integer id) {
		try {
			BigClass bigClass = (BigClass) InitDao.getDao().getEntity(BigClass.class, id);
			bigClass.setName(bigClassName);
			bigClass.setWeight(weight);
			InitDao.getDao().updateEntity(bigClass);
			monitorService.getBigClasses();
			List<SmallClass> smallClasses = smallClassService.findByBigClass(id);
			for (SmallClass smallClass : smallClasses) {
				smallClass.setBigClassName(bigClassName);
				smallClass.setCreateTime(new Timestamp(System.currentTimeMillis()));
				InitDao.getDao().updateEntity(smallClass);
			}
			monitorService.getSmallClasses();
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	public void savePic(MultipartFile multipartFile, String breadId, String picType, HttpServletRequest request) throws IOException {
		String newName = fileUploadService.uploadFile(multipartFile, request);
		MyBread myBread = (MyBread) InitDao.getDao().getEntity(MyBread.class, Integer.valueOf(breadId));
		if (picType.equals("1")) {
			myBread.setSmallPicUrl(newName);
			InitDao.getDao().updateEntity(myBread);
			monitorService.getBread();
		} else if (picType.equals("2")) {
			myBread.setBigPicUrl(newName);
			InitDao.getDao().updateEntity(myBread);
			monitorService.getBread();
		} else {
			BreadPic breadPic = new BreadPic();
			breadPic.setBreadId(Integer.valueOf(breadId));
			breadPic.setCreateTime(new Timestamp(System.currentTimeMillis()));
			breadPic.setName(myBread.getName());
			breadPic.setPicUrl(newName);
			InitDao.getDao().addEntity(breadPic);
		}
	}

	public int addComment(Integer breadId, String commentTitle, String commentContent, String ip) {
		Date now = new Date();
		Date passed5Min = DateUtils.addMinutes(now, -5);
		int count = InitDao.getDao().findEntities("from MyComment c where c.createTime<=? and c.createTime>=?", new Object[] { now, passed5Min }).size();
		if (count > 4) {
			return -1;
		}
		MyComment comment = new MyComment();
		comment.setBreadId(breadId);
		MyBread bread = (MyBread) InitDao.getDao().getEntity(MyBread.class, breadId);
		comment.setBreadName(bread.getName());
		comment.setCommentContent(commentContent);
		comment.setCommentTitle(commentTitle);
		comment.setCreateTime(new Timestamp(System.currentTimeMillis()));
		comment.setIp(ip);
		InitDao.getDao().addEntity(comment);
		return 1;
	}

	public int addCommentBase(String commentTitle, String commentContent, String ip) {
		Date now = new Date();
		Date passed5Min = DateUtils.addMinutes(now, -5);
		int count = InitDao.getDao().findEntities("from MyComment c where c.createTime<=? and c.createTime>=?", new Object[] { now, passed5Min }).size();
		if (count > 4) {
			return -1;
		}
		MyComment comment = new MyComment();
		comment.setBreadId(0);
		comment.setBreadName("");
		comment.setCommentContent(commentContent);
		comment.setCommentTitle(commentTitle);
		comment.setCreateTime(new Timestamp(System.currentTimeMillis()));
		comment.setIp(ip);
		InitDao.getDao().addEntity(comment);
		return 1;
	}

	public List<MyComment> findCommentsByBreadId(Integer breadId) {
		List<MyComment> comments = InitDao.getDao().findEntities("from MyComment c where c.breadId=?", breadId);
		return comments;
	}

	public List<MyBread> findByBigClassId(Integer bigClassId) {
		List<MyBread> breads = InitDao.getDao().findEntities("from MyBread b where b.bigClassId=?", new Object[] { bigClassId });
		return breads;
	}

	public List<MyBread> findBySmallClassId(Integer smallClassId) {
		List<MyBread> breads = InitDao.getDao().findEntities("from MyBread b where b.smallClassId=?", new Object[] { smallClassId });
		return breads;
	}

	public Map<Integer, List<MyBread>> getBreadsMap(List<SmallClass> smallClasses) {
		Map<Integer, List<MyBread>> map = new HashMap<Integer, List<MyBread>>();
		for (SmallClass smallClass : smallClasses) {
			map.put(smallClass.getId(), new ArrayList<MyBread>());
		}
		List<MyBread> myBreads = InitDao.getDao().findEntities("from MyBread m order by m.code");
		for (MyBread myBread : myBreads) {
			if (map.get(myBread.getSmallClassId()) == null) {
				continue;
			}
			map.get(myBread.getSmallClassId()).add(myBread);
		}
		return map;
	}

	public int delComment(Integer id) {
		try {
			MyComment comment = (MyComment) InitDao.getDao().getEntity(MyComment.class, id);
			InitDao.getDao().delEntity(comment);
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	public int deljoinUs(Integer id) {
		try {
			JoinUs joinUs = (JoinUs) InitDao.getDao().getEntity(JoinUs.class, id);
			InitDao.getDao().delEntity(joinUs);
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	public List<BreadPic> findBreadPicsByBreadId(Integer breadId) {
		List<BreadPic> breadPics = InitDao.getDao().findEntities("from BreadPic c where c.breadId=?", breadId);
		return breadPics;
	}

	public List<BreadPrice> findBreadPricesByBreadId(Integer breadId) {
		List<BreadPrice> breadPrices = InitDao.getDao().findEntities("from BreadPrice c where c.breadId=?", breadId);
		return breadPrices;
	}

	public int delBreadPic(Integer id) {
		try {
			BreadPic breadPic = (BreadPic) InitDao.getDao().getEntity(BreadPic.class, id);
			InitDao.getDao().delEntity(breadPic);
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	public int delBreadPrice(Integer id) {
		try {
			BreadPrice breadPrice = (BreadPrice) InitDao.getDao().getEntity(BreadPrice.class, id);
			InitDao.getDao().delEntity(breadPrice);
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	public int addPrice(int breadId, String size, String price) {
		try {
			BreadPrice breadPrice = new BreadPrice();
			breadPrice.setBreadId(Integer.valueOf(breadId));
			breadPrice.setCreateTime(new Timestamp(System.currentTimeMillis()));
			breadPrice.setSize(size);
			breadPrice.setPrice(price);
			InitDao.getDao().addEntity(breadPrice);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	public List<MyBread> findBreads(String name, String code, int pageNo) {
		if (pageNo == 0) {
			pageNo = 1;
		}
		if (StringUtils.isBlank(name) && StringUtils.isBlank(code)) {
			List<MyBread> myBreads = InitDao.getDao().findEntitiesForPage("from MyBread b", pageNo, 20, new Object[] {});
			return myBreads;
		}
		List<MyBread> myBreads = InitDao.getDao().findEntitiesForPage("from MyBread b where b.name like ? and b.code like ? order by b.id desc ", pageNo, 20,
				new Object[] { "%" + name + "%", "%" + code + "%" });
		return myBreads;
	}
}
